package com.fast.fast.common.gateway.config;

import com.fast.fast.common.gateway.handler.GlobalExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.WebFilter;

/**
 * 网关配置类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@Configuration(proxyBeanMethods = false)
public class GatewayConfig {

    /**
     * context-path
     */
    @Value("${server.servlet.context-path:fast-common-gateway}")
    private String prefix;

    /**
     * 过滤server.servlet.context-path属性配置的项目路径，防止对后续路由策略产生影响，因为gateway网关不支持servlet
     *
     * @return
     */
    @Bean
    public WebFilter apiPrefixFilter() {
        return (exchange, chain) ->
        {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getRawPath();
            path = path.startsWith(prefix) ? path.replaceFirst(prefix, "") : path;
            ServerHttpRequest newRequest = request.mutate().path(path).build();
            return chain.filter(exchange.mutate().request(newRequest).build());
        };
    }

    /**
     * 跨域配置
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(false);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

    @Bean
    public GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

}
